<?php

class Ticket_type
{
    public $id;
    public $title;
    public $body;
    public $type_name;
    public $free_beer;
    public $channel;
    public $gift;
    public $price;

    public static function getElementById($nid)
    {
        $node = node_load($nid);
        if($node !== FALSE) return self::toModel($node);
        return NULL;
    }

    public static function toModel($node)
    {
        $model = new Ticket_type();
        $model->id = $node->nid;
        $model->title = $node->title;

        $temp = field_get_items('node', $node, 'body');
        $model->body = $temp[0]['value'];

        $temp = field_get_items('node', $node, 'field_type_name');
        if(count($temp) > 0) $model->type_name = $temp[0]['value'];

        $temp = field_get_items('node', $node, 'field_free_beer');
        if(count($temp) > 0) $model->free_beer = $temp[0]['value'];

        $temp = field_get_items('node', $node, 'field_channel');
        if(count($temp) > 0) $model->channel = $temp[0]['value'];

        $temp = field_get_items('node', $node, 'field_gift');
        if(count($temp) > 0) $model->gift = $temp[0]['value'];

        $temp = field_get_items('node', $node, 'field_price');
        if(count($temp) > 0) $model->price = $temp[0]['value'];

        return $model;
    }


    public function save()
    {
        if($this->id == '')
        {
            global $user;

            // Create node with default values.
            $entity = entity_create('node', array(
                'type' => 'card',
                'uid' => $user->uid,
                'status' => 1,
                'comment' => 1,
                'promote' => 0,
                'created' => time(),
                'language' => LANGUAGE_NONE
            ));
        }
        else
        {
            $entity = node_load($this->id);

        }

        // Use a wrapper for easy getter and setter.
        $wrapper = entity_metadata_wrapper('node', $entity);
        $wrapper->title->set($this->title);
        $entity->body[LANGUAGE_NONE][0] = array(
            'value' => $this->body,
            'format' => 'full_html',
        );

        $wrapper->field_type_name->set($this->type_name);
        $wrapper->field_free_beer->set($this->free_beer);
        $wrapper->field_channel->set($this->channel);
        $wrapper->field_gift->set($this->gift);
        $wrapper->field_price->set($this->price);

        // Save all values to node.
        $wrapper->save(TRUE);

        // Save node to db.
        entity_save('node', $entity);

    }

}

?>